package zqkcom.atguigu.service.impl;

import zqkcom.atguigu.bean.*;
import zqkcom.atguigu.dao.BookDao;
import zqkcom.atguigu.dao.OrderDao;
import zqkcom.atguigu.dao.OrderItemDao;
import zqkcom.atguigu.dao.impl.BookDaoImpl;
import zqkcom.atguigu.dao.impl.OrderDaoImpl;
import zqkcom.atguigu.dao.impl.OrderItemDaoImpl;
import zqkcom.atguigu.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();


    @Override
    public String checkOut(Cart cart, User user) {
        /**
         * 结账：
         *  1、保存订单
         *  2、保存订单项  -->改错
         *  3、更新库存和销量
         */
        //将当前时间所对应的时间戳（即毫秒数）作为订单编号
        String orderId = System.currentTimeMillis() +"";
        //获取系统当前时间，即订单的创建时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = sdf.format(date);
        //将购物车对象转换为订单对象
        Order order = new Order(orderId, createTime, cart.getTotalCount(), cart.getTotalAmount(), 0, user.getId());
        //结账第一步：保存订单
        orderDao.saveOrder(order);
        //获取购物车中的所有购物项
        List<CartItem> cartItemList = cart.getCartItemList();
        //循环所有的购物项，将购物项转换为订单项
        for (CartItem cartItem : cartItemList) {
            //通过购物项对象获取订单项对象
            Book book = cartItem.getBook();
            OrderItem orderItem = new OrderItem(null, book.getTitle(), book.getAuthor(), book.getPrice(), book.getImgPath(), cartItem.getCount(), cartItem.getAmount(), orderId);
            //结账第二步：保存订单项
            orderItemDao.saveOrderItem(orderItem);
            //结账第三步：更新库存和销量
            bookDao.updateSalesAndStock(book.getId(),cartItem.getCount());
        }
        return  orderId;
    }
    @Override
    public List<Order> getMyOrder(Integer userId) {//订单操作

        return orderDao.getMyOrder(userId);
    }

    @Override
    public List<Order> getAllOrder() {//订单操作

        return orderDao.getAllOrder();
    }

    @Override
    public List<OrderItem> getDetails(String orderId) {//查看所有的订单详情

        return orderItemDao.getDetails(orderId);
    }

    @Override
    public void sendOrder(String orderId) {//发货

        orderDao.updateStatus(orderId,1);
    }

    @Override
    public void takeOrder(String orderId) {//收货
        orderDao.updateStatus(orderId,2);

    }
}
